using System;
using System.Collections.Generic;
using System.Text;
using System.Media;

namespace AleaPlayer
{
    public class TWavePlayer<T>
    {
        public delegate void FinishedPlayingDelegate(T item);

        FinishedPlayingDelegate _finishedPlayingDelegate = null;
        List<TSoundPlayerWithItem<T>> _players = null;

        public TWavePlayer(FinishedPlayingDelegate finishedPlayingDelegate)
        {
            _players = new List<TSoundPlayerWithItem<T>>();
            _finishedPlayingDelegate = finishedPlayingDelegate;
        }

        public void StartPlaying(string fileName, T item)
        {
            TSoundPlayerWithItem<T> _realEntry = null;
            TSoundPlayerWithItem<T> _predicate = new TSoundPlayerWithItem<T>(null, item, null);

            if (_players.Contains(_predicate))
            {
                int ix = _players.IndexOf(_predicate);
                if (ix >= 0)
                    _realEntry = _players[ix];
            }
            else
            {
                _realEntry = new TSoundPlayerWithItem<T>(
                                new SoundPlayer(fileName), 
                                item,
                                new TSoundPlayerWithItem<T>.FinishedPlayingDelegate(FinishedPlayingHandler)
                                );
                _players.Add(_realEntry);
            }

            // here _realEntry should be set
            if (_realEntry == null)
                throw new ApplicationException("Failed assertion: _realEntry == null");

            _realEntry.PlaySound();
        }

        public void StopPlaying()
        {
            foreach(TSoundPlayerWithItem<T> lentry in _players)
            {
                lentry.StopSound();
            }
        }

        public bool IsPlaying
        {
            get
            {
                bool retval = false;

                foreach (TSoundPlayerWithItem<T> lentry in _players)
                {
                    retval = lentry.IsPlaying;
                    if (retval)
                        break;
                }

                return retval;
            }
        }

        private void FinishedPlayingHandler(T item)
        {
            if (_finishedPlayingDelegate != null)
                _finishedPlayingDelegate(item);
        }
    }
}
